package com.tjh4.connection;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.jupiter.api.Test;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @ClassName DBCPTest
 * @Description : DBCP连接池技术测试
 * @Author tang'jia'hao
 * @Date 2021/9/25 17:10
 * @Version 1.0
 **/
public class DBCPTest {

    @Test
    public void testGetConnection() throws SQLException {
        // 创建DBCP的数据库连接池
        BasicDataSource source = new BasicDataSource();

        // 设置基本信息
        source.setDriverClassName("com.mysql.cj.jdbc.Driver");
        source.setUrl("jdbc:mysql://localhost:3306/test");
        source.setUsername("root");
        source.setPassword("tjh20010228");

        // 设置其他涉及数据库连接池管理的相关属性
        source.getInitialSize();
        source.setMaxActive(10);

        Connection conn = source.getConnection();
        System.out.println("conn = " + conn);
    }

    // 使用配置文件
    @Test
    public void testGetConnection1() throws Exception {
        Properties pros = new Properties();

        // 方式一
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("dbcp.properties");
        // 方式二
//        FileInputStream is = new FileInputStream(new File("src/dbcp.properties"));

        pros.load(is);
        DataSource source = BasicDataSourceFactory.createDataSource(pros);

        Connection conn = source.getConnection();
        System.out.println("conn = " + conn);
    }
}
